package com.kfm.base;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        // 创建三个 Element 对象
        Element e1 = new Element(1, "张三");
        Element e2 = new Element(2, "李四");
        Element e3 = new Element(3, "王五");

        Set<Element> set = new HashSet<>();
        // 将 element 对象存入 set 集合
        set.add(e1);
        set.add(e2);
        set.add(e3);

        System.out.println(set.size()); // 3

        // 修改 e2 的 hash 字段
        e2.setHash(4);
        // 再次将 e2 存入 set 集合
        set.add(e2);

        System.out.println(set.size()); // 输出多少, 为什么
        System.out.println(set);


    }
}

class Element {

    private int hash;

    private String name;


    public Element(int hash, String name) {
        this.hash = hash;
        this.name = name;
    }

    public void setHash(int hash) {
        this.hash = hash;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Element element = (Element) o;
        return hash == element.hash;
    }

    @Override
    public int hashCode() {
        return Objects.hash(hash);
    }

    @Override
    public String toString() {
        return "Element{" +
                "hash=" + hash +
                ", name='" + name + '\'' +
                '}';
    }
}
